package com.xhdd.serv;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.query_dsl.MatchQuery;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.elasticsearch.core.bulk.BulkResponseItem;
import co.elastic.clients.elasticsearch.core.search.Hit;
import com.xhdd.dto.User;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    ElasticsearchClient esClient;
    String indexName = "user";

    @Override
    public String addUser(User user) throws IOException {
        IndexResponse response = esClient.index(r -> {
            r.index(indexName).document(user);
            return r;
        });
        return response.id();
    }

    public List<BulkResponseItem> bulkAddUser(List<User> list) throws IOException {
        BulkRequest.Builder bl = new BulkRequest.Builder();
        for (User user : list) {
            bl.operations(op -> op.index(idx -> idx.index(indexName).id(user.getId()).document(user)));
        }

        BulkResponse bulk = esClient.bulk(bl.build());
        if (bulk.errors()) {
            for (BulkResponseItem item : bulk.items()) {
                System.out.println(item.error().reason());
            }
        }
        return bulk.items();
    }

    public String delUserById(String userId) throws IOException {
        DeleteResponse delete = esClient.delete(d -> d.index(indexName).id(userId));
        return delete.result().jsonValue();
    }

    public String updtUserById(User user, String userId) throws IOException {
        UpdateResponse<User> update = esClient.update(u -> u.index(indexName).id(userId).doc(user), User.class);
        return update.id();
    }

    public List<User> getUserList(String field, String val) throws IOException {
        List<User> list = new ArrayList<>();
        SearchResponse<User> resp = esClient.search(s -> s.index(indexName).query(q -> q.match(
                MatchQuery.of(b -> b.field(field).query(val)))), User.class);
        for (Hit<User> hit : resp.hits().hits()) {
            list.add(hit.source());
        }
        return list;
    }

}
